package com.tianhua.amis4j.service.parser;

import com.coderman.model.meta.annotations.Template;
import com.coderman.model.meta.bean.dsl.ICURDParse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * date: 2022/2/12
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class TemplateParseContainer implements ApplicationContextAware {

    private static Map<String, ICURDParse> templateParseBeanMap = new HashMap<>();

    public ICURDParse getParseService(String webArchName, String templateName){
        String key = webArchName + "-" + templateName;
        return templateParseBeanMap.get(key);
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> templateBeanMap = applicationContext.getBeansWithAnnotation(Template.class);

        for (Map.Entry<String, Object> entry : templateBeanMap.entrySet()) {
            Template template = AopUtils.getTargetClass(entry.getValue()).getAnnotation(Template.class);
            if(StringUtils.isNotEmpty(template.name())) {
                String key = template.webArchName() + "-" + template.name();
                templateParseBeanMap.put(key,(ICURDParse) entry.getValue());
            }
        }
    }
}
